package com.taxi.interceptor;

import com.taxi.constant.TokenConstants;
import com.taxi.dto.TokenResult;
import com.taxi.result.Result;
import com.taxi.result.ResultCodeEnum;
import com.taxi.util.JwtUtils;
import com.taxi.util.RedisPrefixUtils;
import net.sf.json.JSONObject;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.util.ObjectUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;

/**
 * @Author: aniu
 * @Date: 2023/9/21
 * @ClassName: JwtInterceptor
 * @Description: 拦截器
 * @Version: 1.0
 */

public class JwtInterceptor implements HandlerInterceptor {
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //获取token
        boolean result = true;
        String resultString = "";

        String token = request.getHeader("Authorization");
        //解析token
        TokenResult tokenResult = JwtUtils.checkToken(token);



        if (ObjectUtils.isEmpty(tokenResult)) {
            resultString = "token invalid";
            result = false;
        } else {
            //拼接key
            String phone = tokenResult.getPhone();
            String identity = tokenResult.getIdentity();

            String tokenKey = RedisPrefixUtils.generatorTokenKey(phone, identity, TokenConstants.ACCESS_TOKEN_TYPE);

            //从redis中取出token
            String tokenRedis = stringRedisTemplate.opsForValue().get(tokenKey);
            //判断redis中取出的token是否是空白的
            if (StringUtils.isBlank(tokenRedis)||(!token.trim().equals(tokenRedis.trim()))) {
                resultString = "access token invalid";
                result = false;
            }

        }

        if (!result) {
            PrintWriter out = response.getWriter();
            out.print(JSONObject.fromObject(Result.fail(null,ResultCodeEnum.TOKEN_ERROR)).toString());
        }
        return result;
    }
}
